package com.uzai.console.service.rocketmq.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.utils.MqTopics;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.rocketmq.alarm.AlarmMsgDto;
import com.uzai.console.service.rocketmq.AlarmMsgPushProducerService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: liuqi
 * @Date: 2021/11/15 14:45
 * @Description:
 */
@Service
public class AlarmMsgPushProducerServiceImpl implements AlarmMsgPushProducerService {
    private static Logger logger = LoggerFactory.getLogger(AlarmMsgPushProducerServiceImpl.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    private static final int TOTAL_RETRY = 2;

    /**
     * 发送普通消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param alarmMesDto
     */
    @Override
    public void sendAlarmMessage(AlarmMsgDto alarmMesDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(alarmMesDto));
        logger.info("异常提醒消息参数msg:{}",msg);
        if (alarmMesDto.getRetry() < TOTAL_RETRY){
            rocketMQTemplate.asyncSend(MqTopics.SYS_MSG , msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    logger.info(Tools.getStrEmpty(JSONObject.toJSONString(sendResult)));
                }

                @Override
                public void onException(Throwable throwable) {
                    logger.error("err:",throwable);
                    alarmMesDto.setRetry(alarmMesDto.getRetry()+1);
                    sendAlarmMessage(alarmMesDto);
                }
            });
        }else {
            logger.info("retry fail:{}",msg);
        }
    }
}
